// weather-mcp.js - Cursor MCP 天气查询工具
const { ServerStreaming } = require('@anthropic-ai/sdk');
const axios = require('axios');

// 为MCP服务器创建工具定义
const tools = [
  {
    name: 'query_weather',
    description: '查询指定城市的当前天气情况',
    parameters: {
      type: 'object',
      properties: {
        city: {
          type: 'string',
          description: '城市名称，例如：北京、上海、广州',
        },
      },
      required: ['city'],
    },
    handler: async ({ city }) => {
      try {
        const weatherData = await getWeatherData(city);
        return {
          result: weatherData
        };
      } catch (error) {
        return {
          error: `获取天气数据失败: ${error.message}`
        };
      }
    },
  },
];

// Open-Meteo API获取天气数据
async function getWeatherData(cityName) {
  try {
    // 1. 先通过城市名称获取经纬度
    const geoResponse = await axios.get(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(cityName)}&count=1&language=zh`);
    
    if (!geoResponse.data.results || geoResponse.data.results.length === 0) {
      throw new Error(`未找到城市 "${cityName}"`);
    }
    
    const cityData = geoResponse.data.results[0];
    const { latitude, longitude, name } = cityData;
    
    // 2. 通过经纬度获取实时天气
    const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m,wind_direction_10m&timezone=auto`;
    const weatherResponse = await axios.get(weatherUrl);
    
    if (!weatherResponse.data || !weatherResponse.data.current) {
      throw new Error('获取天气数据失败');
    }
    
    const current = weatherResponse.data.current;
    const weatherCode = current.weather_code;
    const weatherCondition = getWeatherCondition(weatherCode);
    const windDirection = getWindDirection(current.wind_direction_10m);
    
    return {
      city: name, 
      temperature: `${current.temperature_2m}°C`,
      condition: weatherCondition,
      humidity: `${current.relative_humidity_2m}%`,
      windDirection: windDirection,
      windSpeed: `${current.wind_speed_10m}km/h`
    };
  } catch (error) {
    console.error(`获取${cityName}天气数据失败:`, error);
    throw error;
  }
}

// 根据风向角度获取风向描述
function getWindDirection(degree) {
  const directions = ['北风', '东北风', '东风', '东南风', '南风', '西南风', '西风', '西北风', '北风'];
  return directions[Math.round(degree / 45) % 8];
}

// 根据天气代码获取天气状况描述
function getWeatherCondition(code) {
  const weatherCodeMap = {
    0: '晴天',
    1: '晴天，少云',
    2: '晴间多云',
    3: '多云',
    45: '雾',
    48: '雾凇',
    51: '小毛毛雨',
    53: '中毛毛雨',
    55: '大毛毛雨',
    56: '冻小毛毛雨',
    57: '冻大毛毛雨',
    61: '小雨',
    63: '中雨',
    65: '大雨',
    66: '冻小雨',
    67: '冻大雨',
    71: '小雪',
    73: '中雪',
    75: '大雪',
    77: '雪粒',
    80: '小阵雨',
    81: '中阵雨',
    82: '大阵雨',
    85: '小阵雪',
    86: '大阵雪',
    95: '雷暴',
    96: '雷暴伴随小冰雹',
    99: '雷暴伴随大冰雹'
  };
  
  return weatherCodeMap[code] || `未知天气代码(${code})`;
}

// 处理MCP请求
async function handleRequest(request) {
  // 查找匹配的工具
  const tool = tools.find(t => t.name === request.name);
  if (!tool) {
    return {
      error: `未找到工具 "${request.name}"`
    };
  }
  
  // 调用工具处理函数
  return await tool.handler(request.parameters);
}

// 启动MCP服务器
function startServer() {
  // 当收到stdin消息时处理请求
  process.stdin.on('data', async (data) => {
    try {
      const request = JSON.parse(data.toString());
      
      // 处理特殊请求类型
      if (request.type === 'list_tools') {
        // 返回工具列表
        const response = {
          type: 'list_tools_response',
          tools: tools.map(tool => ({
            name: tool.name,
            description: tool.description,
            parameters: tool.parameters
          }))
        };
        console.log(JSON.stringify(response));
        return;
      }
      
      // 处理工具调用请求
      if (request.type === 'call_tool') {
        const result = await handleRequest(request);
        const response = {
          type: 'call_tool_response',
          result: result
        };
        console.log(JSON.stringify(response));
        return;
      }
      
      // 未知请求类型
      console.log(JSON.stringify({
        type: 'error',
        error: `未知请求类型 "${request.type}"`
      }));
    } catch (error) {
      // 处理解析错误
      console.log(JSON.stringify({
        type: 'error',
        error: `处理请求时出错: ${error.message}`
      }));
    }
  });
  
  // 发送初始化消息
  console.log(JSON.stringify({
    type: 'init',
    version: '1.0',
    name: '天气查询MCP服务'
  }));
}

// 启动服务器
startServer(); 